<!-- views/ClientsAnalysis.vue -->
<template>
  <div class="client-analysis-container">
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon"><User /></el-icon>
            <div class="stat-text">
              <h4>总客户端</h4>
              <el-statistic :value="totalClients" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" style="color: #67C23A;"><SuccessFilled /></el-icon>
            <div class="stat-text">
              <h4>在线客户端</h4>
              <el-statistic :value="onlineClients" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" style="color: #E6A23C;"><Warning /></el-icon>
            <div class="stat-text">
              <h4>可疑客户端</h4>
              <el-statistic :value="suspiciousClients" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" style="color: #F56C6C;"><CircleCloseFilled /></el-icon>
            <div class="stat-text">
              <h4>异常客户端</h4>
              <el-statistic :value="abnormalClients" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
              v-model="searchQuery"
              placeholder="搜索客户端ID或IP地址"
              clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
              v-model="selectedDeviceType"
              placeholder="选择设备类型"
              clearable
          >
            <el-option
                v-for="type in deviceTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 客户端列表 -->
    <el-card class="client-list-card">
      <el-table
          :data="filteredClients"
          style="width: 100%"
          stripe
          @row-click="showClientDetail"
      >
        <el-table-column prop="id" label="客户端ID" width="120" />
        <el-table-column label="设备类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getDeviceTypeTag(row.deviceType)">
              {{ row.deviceType }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : 'info'">
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="150" />
        <el-table-column prop="rounds" label="参与轮次" width="120" />
        <el-table-column prop="lastActive" label="最后活跃" />
        <el-table-column label="安全评分" width="120">
          <template #default="{ row }">
            <el-progress
                :percentage="row.securityScore"
                :color="getSecurityColor(row.securityScore)"
                :show-text="false"
                :stroke-width="16"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 统计分析 -->
    <el-row :gutter="20" class="analysis-charts">
      <el-col :span="12">
        <el-card header="设备类型分布">
          <pie-chart :data="deviceDistribution" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card header="地域分布">
          <bar-chart :data="geoDistribution" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户端详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        :title="`客户端详情 - ${selectedClient?.id}`"
        width="50%"
    >
      <client-detail :client="selectedClient" v-if="selectedClient" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  User,
  SuccessFilled,
  Warning,
  CircleCloseFilled,
  Search
} from '@element-plus/icons-vue'
import PieChart from '@/components/charts/PieChart.vue'
import BarChart from '@/components/charts/BarChart.vue'
import ClientDetail from '@/components/ClientDetail.vue'

// 模拟客户端数据
const generateClients = () => {
  const devices = ['Windows', 'Linux']  // 修改为Windows和Linux
  const statuses = ['online', 'offline']
  const locations = ['北京', '上海', '广州', '成都', '武汉']

  return Array.from({length: 50}, (_, i) => ({
    id: `CLIENT-${1000 + i}`,
    deviceType: devices[Math.floor(Math.random() * devices.length)],
    status: statuses[Math.floor(Math.random() * statuses.length)],
    ip: `192.168.1.${Math.floor(Math.random() * 255)}`,
    rounds: Math.floor(Math.random() * 100),
    lastActive: new Date(Date.now() - Math.random() * 86400000).toLocaleString(),
    securityScore: Math.floor(Math.random() * 40 + 60),
    location: locations[Math.floor(Math.random() * locations.length)],
    network: `${Math.floor(Math.random() * 100)} Mbps`,
    modelVersion: `v${Math.floor(Math.random() * 3 + 1)}.0`
  }))
}

// 响应式数据
const clients = ref(generateClients())
const searchQuery = ref('')
const selectedDeviceType = ref('')
const detailVisible = ref(false)
const selectedClient = ref<any>(null)

// 计算属性
const totalClients = computed(() => clients.value.length)
const onlineClients = computed(() => clients.value.filter(c => c.status === 'online').length)
const suspiciousClients = computed(() => clients.value.filter(c => c.securityScore < 70).length)
const abnormalClients = computed(() => clients.value.filter(c => c.securityScore < 60).length)

const deviceTypes = computed(() => {
  const types = new Set(clients.value.map(c => c.deviceType))
  return Array.from(types).map(t => ({ value: t, label: t }))
})

const filteredClients = computed(() => {
  return clients.value.filter(c => {
    const matchesSearch = c.id.includes(searchQuery.value) ||
        c.ip.includes(searchQuery.value)
    const matchesType = selectedDeviceType.value ?
        c.deviceType === selectedDeviceType.value : true
    return matchesSearch && matchesType
  })
})

// 图表数据
const deviceDistribution = computed<{name: string; value: number}[]>(() => {
  const counts = clients.value.reduce((acc: Record<string, number>, c) => {
    acc[c.deviceType] = (acc[c.deviceType] || 0) + 1
    return acc
  }, {} as Record<string, number>)

  return Object.entries(counts).map(([name, value]) => ({
    name,
    value
  }))
})

const geoDistribution = computed<{name: string; value: number}[]>(() => {
  const counts = clients.value.reduce((acc: Record<string, number>, c) => {
    acc[c.location] = (acc[c.location] || 0) + 1
    return acc
  }, {} as Record<string, number>)

  return Object.entries(counts).map(([name, value]) => ({
    name,
    value
  }))
})

// 方法
const showClientDetail = (client: any) => {
  selectedClient.value = client
  detailVisible.value = true
}

const getDeviceTypeTag = (type: string) => {
  const map: any = {
    Windows: 'success',  // Windows使用success样式
    Linux: 'warning'     // Linux使用warning样式
  }
  return map[type] || 'info'
}

const getSecurityColor = (score: number) => {
  if (score >= 80) return '#67C23A'
  if (score >= 70) return '#E6A23C'
  return '#F56C6C'
}
</script>

<style scoped>
.client-analysis-container {
  padding: 20px;
  background: #f5f6fa;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-3px);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 32px;
  margin-right: 20px;
  color: #409EFF;
}

.stat-text h4 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-secondary);
}

.filter-card {
  margin-bottom: 20px;
}

.client-list-card {
  margin-bottom: 20px;
}

.analysis-charts {
  margin-top: 20px;
}

.el-table {
  cursor: pointer;
}

.el-table :deep(.cell) {
  display: flex;
  align-items: center;
}
</style>